package com.zir.face.service;

import com.aliyun.facebody20191230.Client;
import com.aliyun.facebody20191230.models.GenerateHumanAnimeStyleAdvanceRequest;
import com.aliyun.facebody20191230.models.GenerateHumanAnimeStyleResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
import com.aliyun.teautil.models.RuntimeOptions;
import com.zir.face.constant.Constant;
import com.zir.face.util.FaceUtil;
import com.zir.face.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;



@Service
public class FaceServiceImpl {

    @Autowired
    FaceUtil faceUtil;

    @Autowired
    FileUtil fileUtil;


    public String generateHumanAnimeStyle(MultipartFile file,String style) throws Exception {

        //1.存储照⽚到指定⽬录
        File destFile = fileUtil.storageFile(file);

        //这里往后都是阿里云代码
        Client client = faceUtil.createClient(Constant.ACCESS_KEY_ID, Constant.ACCESS_KEY_SECRET);

        InputStream inputStream = new FileInputStream(destFile);

        GenerateHumanAnimeStyleAdvanceRequest generateHumanAnimeStyleAdvanceRequest = new GenerateHumanAnimeStyleAdvanceRequest()
                .setImageURLObject(inputStream)
                .setAlgoType(style);
        RuntimeOptions runtime = new RuntimeOptions();
        try {

            // 复制代码运行请自行打印 API 的返回值
            GenerateHumanAnimeStyleResponse response = client.generateHumanAnimeStyleAdvance(generateHumanAnimeStyleAdvanceRequest, runtime);

            // 获取整体结果
            System.out.println("人物动漫化处理结果："+com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response)));

            return analysisGenerateHumanAnimeStyleResponse(response);//处理之后的新的图片

        } catch (TeaException error) {

            // 获取整体报错信息
            System.out.println(com.aliyun.teautil.Common.toJSONString(error));

            // 获取单个字段
            System.out.println(error.getCode());
        }


        return "fail";
    }

    private String analysisGenerateHumanAnimeStyleResponse(GenerateHumanAnimeStyleResponse resp)
    {
        return resp.getBody().getData().imageURL;
    }

}
